package run.iget.admin.system.service.impl;

import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;

import org.springframework.stereotype.Service;

import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;

import cn.hutool.core.collection.CollUtil;
import run.iget.admin.system.entity.DataDictionary;
import run.iget.admin.system.mapper.DataDictionaryMapper;
import run.iget.admin.system.service.DataDictionaryService;

/**
 * <p>
 * 系统数据字典表 服务实现类
 * </p>
 *
 * @author 大周
 * @since 2022-02-07
 */
@Service
public class DataDictionaryServiceImpl extends ServiceImpl<DataDictionaryMapper, DataDictionary>
        implements DataDictionaryService {

    @Override
    public List<DataDictionary> tree(DataDictionary dataDictionary) {
        List<DataDictionary> list = super.list(QueryWrapper.create(dataDictionary));
        if (CollUtil.isEmpty(list)) {
            return null;
        }

        Long maxId = list.stream().mapToLong(DataDictionary::getId).max().orElse(0);
        AtomicLong atomicLong = new AtomicLong(maxId);

        Map<String, List<DataDictionary>> collect = list.stream()
                .collect(Collectors.groupingBy(DataDictionary::getGroupCode, Collectors.toList()));
        return collect.entrySet().stream().map(entry -> {
            DataDictionary dictionary = new DataDictionary();
            dictionary.setId(atomicLong.incrementAndGet());
            dictionary.setGroupCode(entry.getKey());
            dictionary.setChildren(entry.getValue());
            return dictionary;
        }).collect(Collectors.toList());
    }

}
